/*
 * @Description:
 * @Author: william
 * @Date: 2024-10-16 15:33:29
 * @LastEditors: william
 * @LastEditTime: 2025-05-08 19:26:29
 */

export const useBaseMapMixin = _this => {
  const { satelliteMap = false, mapId, zoom } = _this
  const aMapScale = ref(null)
  const map = ref(null)
  const { theme, language, map: mapType } = storeToRefs(useAppStore())

  watch(mapType, () => {
    showMapLayer()
  })

  const initCountry = () => {
    // 简易行政区图+标注
    return new AMap.DistrictLayer.Country({
      zIndex: 10,
      SOC: 'CHN',
      depth: 1,
      styles: {
        'nation-stroke': '#ff0000',
        'coastline-stroke': '#0088ff',
        'province-stroke': '#888888'
      }
    })
  }

  // 初始化地图
  const initMapModel = (mapCenter = '') => {
    const langStr = localStorage.getItem('language') === 'en' ? 'en' : 'zh_cn'
    map.value = new AMap.Map(mapId, {
      resizeEnable: true,
      expandZoomRange: true,
      zoom: zoom,
      zooms: [3, 20],
      center: mapCenter,
      lang: langStr
    })
    showMapLayer()
    switchTheme()
    // 增加比例尺控件
    aMapScale.value = new AMap.Scale({
      visible: true
    })
    map.value.addControl(aMapScale.value)
  }

  const showMapLayer = () => {
    nextTick(() => {
      if (!map.value) return
      map.value.setLayers([
        mapType.value === 'GMAP' ? getGoogleMapLayer() : getAMapLayer()
      ])
    })
  }

  const switchTheme = () => {
    // 目前只支持高度地图主题切换
    if (mapType.value === 'AMAP') {
      const mapStyleStr =
        theme.value === 'theme-white'
          ? 'amap://styles/fresh'
          : 'amap://styles/bb0a5ebbb974d02e6e4431fc1b33ef65'
      map.value.setMapStyle(mapStyleStr)
    }
  }

  const getAMapLayer = () => {
    return satelliteMap.value
      ? new AMap.TileLayer.Satellite({
          zIndex: 1
        })
      : new AMap.TileLayer({
          zIndex: 1
        })
  }

  const getGoogleMapLayer = () => {
    const lyrs = satelliteMap.value ? 's' : 'm'
    const hl = language.value === 'zh' ? 'zh-CN' : 'en-us'
    return new AMap.TileLayer({
      tileUrl: `https://googlemap.neoway.com/maps/vt/lyrs=${lyrs}@142&hl=${hl}&gl=cn&x=[x]&y=[y]&z=[z]&s=Galile`,
      zIndex: 1
    })
  }

  return {
    map,
    aMapScale,
    theme,
    language,
    initCountry,
    initMapModel,
    showMapLayer,
    switchTheme,
    getAMapLayer,
    getGoogleMapLayer
  }
}
